import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '用户登录',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: {
      title: '用户注册',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  // 删除总的 /dashboard 路由
  
  // 学生端路由 - 完全独立
  {
    path: '/student',
    component: () => import('@/layout/StudentLayout.vue'),
    meta: {
      title: '学生中心',
      requiresAuth: true,
      userType: 'S'
    },
    children: [
      {
        path: '',
        name: 'StudentHome',
        redirect: '/student/dashboard'
      },
      {
        path: 'dashboard',
        name: 'StudentDashboard',
        component: () => import('@/views/student/Dashboard.vue'),
        meta: {
          title: '学生工作台',
          breadcrumb: [
            { title: '学生中心', path: '/student' },
            { title: '工作台', path: '/student/dashboard' }
          ]
        }
      },
      {
        path: 'title-check',
        name: 'TitleCheck',
        component: () => import('@/views/student/TitleCheck.vue'),
        meta: {
          title: '题目查重',
          breadcrumb: [
            { title: '学生中心', path: '/student' },
            { title: '题目查重', path: '/student/title-check' }
          ]
        }
      },
      {
        path: 'paper-check',
        name: 'PaperCheck',
        component: () => import('@/views/student/PaperCheck.vue'),
        meta: {
          title: '论文查重',
          breadcrumb: [
            { title: '学生中心', path: '/student' },
            { title: '论文查重', path: '/student/paper-check' }
          ]
        }
      },
      {
        path: 'info-extraction',
        name: 'InfoExtraction',
        component: () => import('@/views/student/InfoExtraction.vue'),
        meta: {
          title: '信息提取',
          breadcrumb: [
            { title: '学生中心', path: '/student' },
            { title: '信息提取', path: '/student/info-extraction' }
          ]
        }
      }
    ]
  },
  // 教师端路由 - 完全独立
  {
    path: '/teacher',
    component: () => import('@/layout/TeacherLayout.vue'),
    meta: {
      title: '教师管理',
      requiresAuth: true,
      userType: 'T'
    },
    children: [
      {
        path: '',
        name: 'TeacherHome',
        redirect: '/teacher/dashboard'
      },
      {
        path: 'dashboard',
        name: 'TeacherDashboard',
        component: () => import('@/views/teacher/Dashboard.vue'),
        meta: {
          title: '教师工作台',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '工作台', path: '/teacher/dashboard' }
          ]
        }
      },
      {
        path: 'students',
        name: 'StudentManagement',
        component: () => import('@/views/teacher/StudentManagement.vue'),
        meta: {
          title: '学生管理',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '学生管理', path: '/teacher/students' }
          ]
        }
      },
      {
        path: 'submissions',
        name: 'SubmissionManagement',
        component: () => import('@/views/teacher/SubmissionManagement.vue'),
        meta: {
          title: '提交记录',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '提交记录', path: '/teacher/submissions' }
          ]
        }
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('@/views/teacher/Statistics.vue'),
        meta: {
          title: '统计分析',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '统计分析', path: '/teacher/statistics' }
          ]
        }
      },
      {
        path: 'settings',
        name: 'TeacherSettings',
        component: () => import('@/views/teacher/Settings.vue'),
        meta: {
          title: '系统设置',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '系统设置', path: '/teacher/settings' }
          ]
        }
      },
      {
        path: 'logs',
        name: 'OperationLogs',
        component: () => import('@/views/teacher/Logs.vue'),
        meta: {
          title: '操作日志',
          breadcrumb: [
            { title: '教师管理', path: '/teacher' },
            { title: '操作日志', path: '/teacher/logs' }
          ]
        }
      }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false,
      hideInMenu: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  try {
    console.log('路由守卫开始:', {
      fromPath: from.path,
      toPath: to.path,
      timestamp: new Date().toISOString()
    })
    
    // 动态导入 store，确保 Pinia 已初始化
    const { useUserStore } = await import('@/stores/user')
    const { useAppStore } = await import('@/stores/app')
    
    const userStore = useUserStore()
    const appStore = useAppStore()
    
    console.log('路由守卫检查:', {
      from: from.path,
      to: to.path,
      isLoggedIn: userStore.isLoggedIn,
      hasToken: !!userStore.token,
      userType: userStore.userInfo?.userType,
      tokenValue: userStore.token,
      userInfoValue: userStore.userInfo
    })
    
    // 设置页面标题
    if (to.meta.title) {
      appStore.setPageTitle(to.meta.title)
    }
    
    // 设置面包屑
    if (to.meta.breadcrumb) {
      appStore.setBreadcrumbs(to.meta.breadcrumb)
    }
    
    // 处理根路径重定向
    if (to.path === '/') {
      if (userStore.isLoggedIn) {
        const userType = userStore.userInfo?.userType
        if (userType === 'S') {
          next('/student/dashboard')
        } else if (userType === 'T') {
          next('/teacher/dashboard')
        } else {
          next('/login')
        }
      } else {
        next('/login')
      }
      return
    }
    
    // 如果访问登录页面
    if (to.path === '/login') {
      if (userStore.isLoggedIn) {
        const userType = userStore.userInfo?.userType
        console.log('已登录，重定向到工作台，用户类型:', userType)
        if (userType === 'S') {
          next('/student/dashboard')
        } else if (userType === 'T') {
          next('/teacher/dashboard')
        } else {
          next('/student/dashboard') // 默认跳转到学生工作台
        }
      } else {
        next()
      }
      return
    }
    
    // 检查是否需要认证
    if (to.meta.requiresAuth) {
      // 导入常量
      const { STORAGE_KEYS } = await import('@/utils/constants')
      
      // 双重检查：从 store 和 localStorage 都检查
      const storeHasAuth = userStore.isLoggedIn
      const localToken = localStorage.getItem(STORAGE_KEYS.TOKEN) || sessionStorage.getItem(STORAGE_KEYS.TOKEN)
      const localUserInfo = localStorage.getItem(STORAGE_KEYS.USER_INFO) || sessionStorage.getItem(STORAGE_KEYS.USER_INFO)
      
      console.log('认证检查:', {
        storeHasAuth,
        hasLocalToken: !!localToken,
        hasLocalUserInfo: !!localUserInfo,
        localStorageToken: localStorage.getItem(STORAGE_KEYS.TOKEN),
        sessionStorageToken: sessionStorage.getItem(STORAGE_KEYS.TOKEN),
        localStorageUserInfo: localStorage.getItem(STORAGE_KEYS.USER_INFO),
        sessionStorageUserInfo: sessionStorage.getItem(STORAGE_KEYS.USER_INFO),
        STORAGE_KEYS
      })
      
      // 如果 store 中没有，但本地存储有，则恢复 store 状态
      if (!storeHasAuth && localToken && localUserInfo) {
        console.log('从本地存储恢复登录状态')
        try {
          const userInfo = JSON.parse(localUserInfo)
          userStore.login(localToken, userInfo)
          console.log('登录状态已恢复')
        } catch (e) {
          console.error('恢复登录状态失败:', e)
        }
      }
      
      // 如果store中没有认证信息，尝试手动恢复
      if (!userStore.isLoggedIn) {
        console.log('尝试手动恢复状态')
        const restored = userStore.forceRestoreState()
        console.log('手动恢复结果:', restored)
      }
      
      // 再次检查登录状态，确保有有效的token
      if (!userStore.isLoggedIn || !userStore.token || userStore.token.length === 0) {
        console.log('未登录，重定向到登录页')
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
      
      // 检查用户类型权限
      const userType = userStore.userInfo?.userType
      const requiredUserType = to.meta.userType
      
      if (requiredUserType && requiredUserType !== userType) {
        let message = '您没有权限访问该页面'
        let redirectPath = '/login'
        
        if (userType === 'S') {
          message = '学生用户无法访问教师管理页面'
          redirectPath = '/student/dashboard'
        } else if (userType === 'T') {
          message = '教师用户无法访问学生中心页面'
          redirectPath = '/teacher/dashboard'
        }
        
        console.log('权限不足:', message)
        ElMessage.warning(message)
        next(redirectPath)
        return
      }
    }
    
    // 正常通过
    console.log('路由守卫通过，跳转到:', to.path)
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    next('/login')
  }
})


export default router